package com.eas.biz.service.exam.impl;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eas.biz.framework.cache.CacheConfig;
import com.eas.biz.framework.cache.CacheProvider;
import com.eas.biz.framework.cache.CacheStore;
import com.eas.biz.service.exam.domain.Exam;
import com.eas.biz.service.exam.domain.ExamQuestionDetail;
import com.eas.biz.service.exam.domain.ExamSubjectDetail;
import com.eas.biz.service.exam.interfaces.ExamService;

@Service("examCacheService")
public class ExamCacheServiceImpl extends ExamServiceImpl implements ExamService {

    @Autowired
    private CacheProvider cacheProvider;

    private CacheStore cacheStore;

    @PostConstruct
    public void init() {
        CacheConfig config = new CacheConfig();
        config.setName("examInfo");
        config.setRefreshSeconds(24 * 60 * 60);
        config.setCapacity(50);
        cacheStore = cacheProvider.create(config);
    }

    @Override
    public Exam getExamDetail(long examId) {
        Object result = cacheStore.get(examId);
        if (result != null && result instanceof Exam) {
            return (Exam) result;
        } else {
            Exam exam = super.getExamDetail(examId);
            if (exam != null) {
                cacheStore.put(examId, exam);
            }
            return exam;
        }
    }

    @Override
    public Exam getSimpleExam(long examId) {
        return getExamDetail(examId);
    }

    public ExamSubjectDetail getExamSubjectDetail(long examId, String subject) {
        Exam exam = getExamDetail(examId);
        return exam != null ? exam.getSubjectDetail(subject) : null;
    }

    public ExamQuestionDetail getExamQuestionDetail(long examId, String subject,
            String questionNumber) {
        ExamSubjectDetail subjectDetail = getExamSubjectDetail(examId, subject);
        return subjectDetail != null ? subjectDetail.getQuestionDetail(questionNumber) : null;
    }
}
